<?php
class ActionController extends BaseController {
	// 检查邮箱是否已经存在
	function emailexistAction() {
		$email = trim($this->_getParam('email'));
		if (empty($email)) {
			print "邮箱不能为空";
			return;
		}
		require 'Xiachufang/logic/Actor.php';
		if (ActorLogic::exist($email)) print '1';
		else print '0';
	}
	
	// 用户登陆
	function actorloginAction() {
		$email = trim($this->_getParam('email'));
		$password = $this->_getParam('password');
		$persist = $this->_getParam('persist');
		$validCode = $this->_getParam('validCode');
		$rurl = $this->_getParam('rurl');
		ob_start();
		session_start();
		$validCodeKey = 'valid_code';
		$sValidCode = strtolower($_SESSION[$validCodeKey]);
		$_SESSION[$validCodeKey] = '';
		session_commit();
		if ($sValidCode && $sValidCode != strtolower($validCode)) {
			alert('验证码错误，请重新输入');
		}
		
		$status = ActorLogic::login($email, $password, $persist);
		if ($status === false) {
			alert("用户名或者密码错误");
		} else if ($status == "0"){
			require_once 'Xiachufang/util/Util.php';
			$host = Util::getEmailHost($email);
			alert(<<<BODY
您的帐号尚未激活。
<ul>
<li><a href="/resend?email=$email">重新发送激活邮件</a></li>
<li><a href="http://{$host["url"]}">点击进入邮箱</a></li>
</ul>
BODY
);
		} else {
			if (!$rurl) $rurl = "/";
			header("Location: ".$rurl);
		}
	}
	
	/**
	 * 添加收藏的操作
	 *
	 */
	function favaddAction() {
		$actorId = $this->_actorId;
		if (!$actorId) {
			echo '0';
			return;
		}
		$recipeId = (int)$this->_getParam('recipeId');
		if ($recipeId <= 0) {
			echo '0';
			return;
		}
		$private = $this->_getParam('private', false);
		require 'Xiachufang/logic/Favorite.php';
		FavoriteLogic::addFavorite($actorId, $recipeId, $private);
		print '1';
	}
	
	/**
	 * 取消收藏
	 *
	 */
	function favcancelAction() {
		$actorId = $this->_actorId;
		if (!$actorId) {
			echo '0';
			return;
		}
		$recipeId = (int)$this->_getParam('recipeId');
		if ($recipeId <= 0) {
			echo '0';
			return;
		}
		$private = $this->_getParam('private', false);
		require 'Xiachufang/logic/Favorite.php';
		FavoriteLogic::deleteFavorite($actorId, $recipeId, $private);
		print '1';
	}
	
	/**
	 * 添加评论
	 *
	 */
	function remarkaddAction() {
		$this->checkLogin();
		$recipeId = (int)$this->_getParam("recipeId");
		$foodId = (int)$this->_getParam("foodId");
		$content = trim(nl2br($_POST["content"]));
		
		if ($recipeId <= 0) throw new Exception("recipeId必须为正整数");
		if (!$content) throw new Exception("评论内容不能为空");
		
		$actorId = $this->_actorId;
		
		$createTime = time();
		require 'Xiachufang/entity/Remark.php';
		$remark = new RemarkEntity();
		$remark->recipeId = $recipeId;
		$remark->foodId = $foodId;
		$remark->content = $content;
		$remark->actorId = $actorId;
		$remark->createTime = $createTime;
		$remark->save();
		
		// 如果foodId大于0，则表示是对食物的评论
		if ($foodId <= 0) {
			require_once 'Xiachufang/logic/Event.php';
			EventLogic::addEvent(EventLogic::REMARK_RECIPE_EVENT, $recipeId, $remark->remarkId, $actorId, $createTime);
		}
		
		$remark = $remark->getDataArray();
		$remark["actorName"] = $this->_actor->nickname;
		require_once 'Xiachufang/util/TimeUtil.php';
		$remark["createTime"] = TimeUtil::format($remark["createTime"]);
		
		$this->smarty->assign_by_ref("remark", $remark);
		$this->smarty->display("part/remark.tpl");
	}
	
	/**
	 * 编辑菜谱
	 *
	 */
	function recipeeditAction() {
		$this->checkLogin();
		$recipeId = (int)$this->_getParam("recipeId");
		if ($recipeId > 0) $this->_addRecipeWiki($recipeId);
		else $this->_addRecipe();
	}
	
 	/* 添加菜谱的wiki版本
	 *
	 * @param unknown_type $recipeId
	 */
	private function _addRecipeWiki($recipeId) {
		require_once 'Xiachufang/entity/Recipe.php';
		$recipe = new RecipeEntity();
		if (!$recipe->get($recipeId)) {
			print '没有找到recipeId='.$recipeId."的菜谱";
			exit;
		}
		$ingredients = trim($_POST["ingredients"]);
		$directions = trim($_POST["directions"]);
		$description = trim($_POST["description"]);
		$skill = trim($_POST["skill"]);
		$costTime = trim($_POST["costTime"]);
		$difficulty = Request::getInt("difficulty");
		$tags = trim($_POST["tags"]);
		
		// 验证和处理表单
		if (!preg_match("/^([a-zA-Z\x{4e00}-\x{9fa5}()（）]+\d+克\s*)+$/u", $ingredients)) {
			print("食谱用料格式错误");
			exit();
		}
		if (!$directions) throw new Exception("食谱做法不能为空");
		$descLen = mb_strlen($description);
		if ($descLen <= 20 || $descLen > 300) throw new Exception("食谱简介需要在20-300字之间");
		$directions = str_replace("\r\n","<br/>", backString($directions));
		$description = str_replace("\r\n","<br/>", backString($description));
		$skill = str_replace("\r\n","<br/>", backString($skill));
		require_once 'Xiachufang/logic/Tag.php';
		$tags = TagLogic::getFomatTags($tags);
		
		$now = time();
		$actorId = $this->_actorId;
		require_once 'Xiachufang/entity/RecipeWiki.php';
		$wiki = new RecipeWikiEntity();
		$wiki->actorId = $actorId;
		$wiki->recipeId = $recipeId;
		$wiki->ingredients = $ingredients;
		$wiki->directions = $directions;
		$wiki->skill = $skill;
		$wiki->description = $description;
		$wiki->costTime = $costTime;
		$wiki->difficulty = $difficulty;
		$wiki->tags = $tags;
		$wiki->createTime = $now;
		
		$wiki->save();
		
		// 增加private=true的事件
		require_once 'Xiachufang/logic/Event.php';
		EventLogic::addEvent(EventLogic::EDIT_RECIPE_EVENT, $recipeId, $wiki->recipeWikiId, $actorId, $now, true);
		
		// 上传图片
		if ($_FILES["picture"]['size'] > 0) {
			$target = dirname(__FILE__)."/pictures/wiki/".$wiki->recipeWikiId.".jpg";
			@move_uploaded_file($_FILES["picture"]['tmp_name'],$target);
		}
		
		header('Location: /wiki/'.$wiki->recipeWikiId);
	}
	
	/**
	 * 添加菜谱
	 *
	 */
	private function _addRecipe() {
		$name = $_POST["recipeName"];
		$checkCode = $_POST["checkCode"];
		if (RecipeLogic::getRecipeNameCheckCode($name) !== $checkCode) throw new Exception("存在对菜谱名称进行非法修改的嫌疑");
		
		$recipes = RecipeLogic::findRecipe($name);
		if ($recipes["same"]) {
			print '<script type="text/javascript">
			if(confirm("已经存在相同名称的菜谱\n点击\"是\"查看，点击\"否\"返回"){
				window.location="/recipe/'.$recipes["same"][0]["recipeId"].'";}else{
				history.go(-1);
			}</script>';
			exit;
		}
		
		$ingredients = trim($_POST["ingredients"]);
		$directions = trim($_POST["directions"]);
		$description = trim($_POST["description"]);
		$skill = trim($_POST["skill"]);
		$costTime = trim($_POST["costTime"]);
		$difficulty = Request::getInt("difficulty");
		$tags = trim($_POST["tags"]);
		
		// 验证和处理表单
		if (!preg_match("/^([a-zA-Z\x{4e00}-\x{9fa5}()（）]+\d+克\s*)+$/u", $ingredients)) {
			print("食谱用料格式错误");
			exit();
		}
		if (!$directions) throw new Exception("食谱做法不能为空");
		$descLen = mb_strlen($description);
		if ($descLen <= 20 || $descLen > 300) throw new Exception("食谱简介需要在20-300字之间");
		$directions = str_replace("\n","<br/>", backString($directions));
		$description = str_replace("\n","<br/>", backString($description));
		$skill = str_replace("\n","<br/>", backString($skill));
		require_once 'Xiachufang/logic/Tag.php';
		$tags = TagLogic::getFomatTags($tags);
		
		require_once 'Xiachufang/entity/Recipe.php';
		$recipe = new RecipeEntity();
		$recipe->actorId = $this->_actorId;
		$recipe->name = $name;
		$recipe->ingredients = $ingredients;
		$recipe->directions = $directions;
		$recipe->skill = $skill;
		$recipe->description = $description;
		$recipe->costTime = $costTime;
		$recipe->difficulty = $difficulty;
		$recipe->tags = $tags;
		$recipe->createTime = time();
		
		$recipe->save();
		
		
		// 上传图片
		if ($_FILES["picture"]['size'] > 0) {
			$target = SITE_DIR."/pictures/recipe/".$recipe->recipeId.".jpg";
			@move_uploaded_file($_FILES["picture"]['tmp_name'],$target);
		}
		
		$this->_redirect('/recipe/'.$recipe->recipeId);
	}
	/**
	 * 修改头像
	 *
	 */
	function facemodifyAction() {
		$this->checkLogin();
		$actorId = $this->_actorId;
		// 上传图片
		$picture = $_FILES["picture"];
		if ($picture) {
			$target = BASE_DIR."/pictures/people/$actorId.jpg";
			@move_uploaded_file($picture['tmp_name'],$target);
			
			require_once 'Xiachufang/util/Util.php';
			Util::thumbPicture($target, $target, 48, 48);
		}
		print "1";
	}
	
	/**
	 * 修改昵称
	 *
	 */
	function nicknamemodifyAction() {
		$this->checkLogin();
		$actorId = $this->_actorId;
		$new = trim($_POST["new"]);
		$len = strlen2($new);
		if ($len <= 0 || $len > 20) {
			print "昵称不能为空且必须小于10个汉字的长度";
			break;
		}
		$this->_actor->nickname = $new;
		$this->_actor->update();
		print "1";
	}
	
	/**
	 * 修改密码
	 *
	 */
	function passwordModify() {
		$this->checkLogin();
		
		require_once 'Xiachufang/logic/Actor.php';
		if (ActorLogic::getPasswordMd5($_POST["oldPassword"]) !== $this->_actor->password) {
			alert("原密码不正确");
		}
		
		$new = $_POST["password"];
		$len = strlen2($new);
		if ($len <= 0 || $len > 20) {
			alert("密码不能为空或大于10个汉字的长度");
		}
		if ($new != $old) {
			$this->_actor->password = ActorLogic::getPasswordMd5($new);
			$this->_actor->update();
		}
		$this->_redirect('/people/'.$this->actorId.'/profile');
	}
}
?>